import Taro, { Component } from '@tarojs/taro'
import { AtTabs, AtTabsPane, AtList, AtListItem, AtButton } from 'taro-ui'
import { View, ScrollView, Image, Text } from '@tarojs/components'
import { DNavBar, DCarInfo, DItemError, DModal } from '@/components'
import './mycollections.scss'
import http from '@/api'
const checkbox = require('../assets/check_box.png')
const checked = require('../assets/ischecked.png')
export default class mycollections extends Component {

  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      footerStatus1: false,
      footerStatus2: false,
      scrollStyle: window.screen.availHeight,
      item1: [],
      item: [],
      page: 1,
      limit: 10,
      order: "",
      sidx: "",
      status: "",
      totalPage: 1,
      item2: [],
      obj2: {
        page: 1,
        limit: 10,
        order: "",
        sidx: "",
        status: "",
      },
      id: '',
      _status: 0,// 全选按钮：1不选中，2选中
      delList: [],
      delLength: 0,
      isModal: false,
      Atcheck: '',
      Atstatus: 0 //企业全选按钮：1不选中 2选中
    }
  }

  componentWillMount() {
    this.getmyCollecticon()
  }
  //企业跳转
  onHandlePlace(id) {
    //管理状态不可跳转
    if (this.state.Atstatus !== 0) {
      return
    }
    Taro.navigateTo({
      url: `/pages/companydetail/companydetail?id=${id}`
    })
  }
  //车源跳转
  handleToDetail(id) {
    //管理状态不可跳转
    if (this.state._status !== 0) {
      return
    }
    Taro.navigateTo({
      url: `/pages/carsourcedetails/carsourcedetails?id=${id}`
    })
  }
  //获取收藏的车源
  getmyCollecticon(id) {
    let { page, limit, order, sidx, status, totalPage, item1, item } = this.state
    let obj = {
      page,
      limit,
      order,
      sidx,
      status,
    }
    if (page > totalPage) {
      this.setState({
        footerStatus1: true
      })
      return
    }
    http.getmyCollecticon(obj).then(res => {
      if (!res) {
        return
      }
      let { _status } = this.state
      let _item1 = []
      res.list.map(_key => {
        _item1.push({
          ..._key,
          isCheck: _status !== 0 ? _status === 1 ? '2' : '1' : ''      //1选中  2不选中
        })
      })
      item1 = [...item, ..._item1]
      this.setState({
        totalPage: res.totalPage || 1,
        item1,
        item: item1
      })
    })
  }
  //获取收藏的企业
  getmyEntry(id) {
    let { obj2, totalPage2, item2, Atstatus } = this.state
    let obj = obj2
    if (obj2.page > totalPage2) {
      this.setState({
        footerStatus2: true
      })
      return
    }
    http.getmyEntry(obj).then(res => {
      if (res.list.length === 0) {
        return
      }
      if (obj2.page > 1) {
        res.list.map(_i => {
          if (_i) {
            item2.push({
              entDis: _i.entDis || '---',
              bussId: _i.id || '---',
              entName: _i.entName || '---',
              isCheck: Atstatus !== 0 ? Atstatus === 1 ? 1 : 2 : 1 //1不选中，2选中
            })
          }
        })
      } else {
        item2 = []
        res.list.map(_i => {
          if (_i) {
            item2.push({
              entDis: _i.entDis || '---',
              bussId: _i.id || '---',
              entName: _i.entName || '---',
              isCheck: Atstatus !== 0 ? Atstatus === 1 ? 1 : 2 : 1  //1不选中，2选中
            })
          }
        })
      }
      this.setState({
        item: item2,
        item2,
        totalPage2: res.totalPage,
      })
    })
  }

  handleClick(value) {
    this.setState({
      active: value,
      item1: [],
      item2: [],
      item: [],
      page: 1,
      limit: 10,
      _status: 0,
      Atstatus: 0,
      Atcheck: '',
      obj2: {
        page: 1,
        limit: 10
      },
      footerStatus1: false,
      footerStatus2: false
    }, () => {
      if (value === 0) {
        this.getmyCollecticon()
      } else if (value === 1) {
        this.getmyEntry()
      }
    })

  }

  onScroll = () => {
    let { active } = this.state
    if (active === 0) {
      this.setState({
        page: this.state.page + 1,
        scrollStyle: window.screen.availHeight
      }, () => this.getmyCollecticon())
    }
    if (active === 1) {
      let { obj2 } = this.state
      obj2.page = obj2.page + 1
      this.setState({
        obj2,
        scrollStyle: window.screen.availHeight
      }, () => this.getmyEntry())
    }

  }

  //判断子项是否全部勾选-->确定全选按钮状态
  isSelectAll(list) {
    let { active } = this.state
    if (active === 0) {
      for (let i = 1; i < list.length; i++) {
        if (list[0].isCheck !== list[i].isCheck) {
          return this.setState({
            _status: 1
          })
        }
        if (list[0].isCheck === '1') {
          this.setState({
            _status: 2
          })
        }

      }
    } else if (active === 1) {
      for (let i = 1; i < list.length; i++) {
        if (list[0].isCheck !== list[i].isCheck) {
          return this.setState({
            Atstatus: 1
          })
        }
        if (list[0].isCheck === 2) {
          this.setState({
            Atstatus: 2
          })
        }
      }
    }
  }
  //车源多选框
  handlecheck(index) {
    let { item } = this.state
    item[index].isCheck = item[index].isCheck === '1' ? '2' : '1'
    this.isSelectAll(item)
    this.setState({
      item
    })
  }
  //企业多选框
  handleAtcheck(index) {
    let { item } = this.state
    item[index].isCheck = item[index].isCheck === 1 ? 2 : 1
    this.isSelectAll(item)
    this.setState({
      item
    })
  }
  //管理按钮
  handleMgr() {
    let { active, item } = this.state
    let _item = []
    if (active === 0) {
      item.map(i => {
        _item.push({
          ...i,
          isCheck: '2'
        })
      })
      this.setState({
        item: _item,
        _status: 1,
      })
    } else if (active === 1) {
      this.setState({
        Atstatus: 1,
        Atcheck: 1
      })
    }
  }
  //车源全选按钮事件
  handleSelAll() {
    let { item, } = this.state
    let _item = []
    item.map(i => {
      _item.push({
        ...i,
        isCheck: this.state._status === 1 ? '1' : '2',
      })
    })
    this.setState({
      item: _item,
      _status: this.state._status === 1 ? 2 : 1,
    })
  }
  //企业全选按钮事件
  handleAtSelAll() {
    let { item, } = this.state
    let _item = []
    item.map(i => {
      _item.push({
        ...i,
        isCheck: this.state.Atstatus === 1 ? 2 : 1,
      })
    })
    this.setState({
      item: _item,
      Atstatus: this.state.Atstatus === 1 ? 2 : 1,
    })
  }
  //车源删除按钮事件
  handleDel() {
    let { item, _status } = this.state
    let delList = []
    if (_status === 2) {
      item.map(_item => {
        delList.push(_item.bussId)
      })
    } else {
      item.map(_item => {
        if (_item.isCheck === '1') {
          delList.push(_item.bussId)
        }
      })
    }
    if (delList.length === 0) {
      return Taro.showToast({
        title: '您还未选中收藏的车源哦!',
        icon: 'none'
      })
    }
    this.setState({
      isModal: true,
      delList,
      modelText: `确定要删除选中的${delList.length}个车源吗？`
    })
  }
  //企业删除按钮事件
  handleAtDel() {
    //删除企业
    let { item, Atstatus } = this.state
    let AtdelList = []
    if (Atstatus === 2) {
      item.map(_item => {
        AtdelList.push(_item.bussId)
      })
    } else {
      item.map(_item => {
        if (_item.isCheck === 2) {
          AtdelList.push(_item.bussId)
        }
      })
    }
    if (AtdelList.length === 0) {
      return Taro.showToast({
        title: '您还未选中收藏的企业哦！',
        icon: 'none'
      })
    }
    this.setState({
      AtdelList,
      isModal: true,
      modelText: `确定要删除选中的${AtdelList.length}个企业吗？`
    })
  }
  //车源/企业删除接口
  delmyCarCollect(arr) {
    http.delmyCarCollect(arr).then(res => {

      Taro.showToast({
        title: '删除成功',
        duration:1000
      }).then(()=>{
        setTimeout(()=>{
          this.handleClick(this.state.active)
        },1000)
      })
    })
  }
  //车源完成按钮
  handleFinish() {
    let { active, item } = this.state
    let _item = []
    if (active === 0) {
      item.map(i => {
        _item.push({
          ...i,
          isCheck: ''
        })
      })
      this.setState({
        item: _item,
        _status: 1,
      })
    }
    this.setState({
      _status: 0
    })
  }
  //企业完成按钮
  handleAtFinish() {
    this.setState({
      Atstatus: 0,
      Atcheck: ''
    })
  }

  handleCancel() {
    this.setState({
      isModal: false
    })
  }
  //删除事件确认
  // onCancel

  onHandlerConfirm() {
    this.handleCancel()
    let { delList, active, AtdelList } = this.state
    if (active === 0) {
      this.delmyCarCollect(delList)
    } else if (active === 1) {
      this.delmyCarCollect(AtdelList)
    }
  }
  render() {
    const tabList = [{ title: '车源' }, { title: '企业' }]
    const {
      active,
      item,
      footerStatus1,
      footerStatus2,
      scrollStyle,
      _status,
      isModal,
      modelText,
      Atcheck,
      Atstatus
    } = this.state
    return (
      <View className='b_mycollections'>
        <DNavBar title={'我的收藏'} className='b_mycollections_nav'></DNavBar>
        <View className='b_mycollections__box'>
          <View className='b_mycollections__content'>
            <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 135}PX`}
                  onScrollToLower={this.onScroll}>
                  {
                    item.length > 0 && item.map((_item, i) => {
                      return <DCarInfo
                        check={_item.isCheck}
                        handlecheck={this.handlecheck.bind(this, i)}
                        key={i}
                        carmoney={_item.carOfferPrice || '--'}
                        nameList={[_item.carDataModel || '--']}
                        infoList={[_item.carSourceType, _item.carEmissionStd, _item.carSourcePt, '外观颜色', _item.carOutColor,]}
                        place={_item.carSourceAddr}
                        money={_item.carGuiPrice}
                        icon={_item.carDataBrandLogo}
                        company={_item.entName + '(' + _item.entDis + ')'}
                        clock={_item.createTime}
                        onDetail={this.handleToDetail.bind(this, _item.bussId)}
                      >
                      </DCarInfo>
                    })
                  }
                  {
                    footerStatus1 && <View className='b_mycollections__footer'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 135}PX`}
                  onScrollToLower={this.onScroll}>
                  <AtList className='b_mycollections__Atlist'>
                    {item && item.map((_item, i) => {
                      return <View className='b_mycollections__flex'>
                        {Atcheck &&
                          <View className='flex__img' key={i} onClick={this.handleAtcheck.bind(this, i)}>
                            <Image src={_item.isCheck === 1 ? checkbox : checked} className='flex__check'></Image>
                          </View>
                        }
                        <AtListItem
                          className='b_mycollections__flex_list'
                          key={i}
                          onClick={this.onHandlePlace.bind(this, _item.bussId)}
                          arrow='right'
                          title={_item.entName}
                          note={_item.entDis}
                        />
                      </View>

                    })
                    }
                  </AtList>
                  {
                    footerStatus2 && <View className='b_mycollections__footer'>暂无更多</View>
                  }
                </ScrollView>

              </AtTabsPane>
            </AtTabs>
          </View>
        </View>
        {item.length === 0 && <DItemError></DItemError>}
        {item.length !== 0 &&
          <View>
            {_status === 0 &&
              <View className='b_mycollections__footer2'>
                <AtButton className='item_btn' onClick={this.handleMgr.bind(this)}>管理</AtButton>
              </View>
            }
            {_status !== 0 &&
              <View className='b_mycollections__footer3'>
                <View className='b_mycollections__footer3_box'>
                  <Image src={_status === 1 ? checkbox : checked} className='b_mycollections__footer3_img' onClick={this.handleSelAll.bind(this)}></Image>
                  <Text className='b_mycollections__footer3_text' onClick={this.handleSelAll.bind(this)}>全选</Text>
                </View>
                <AtButton className='item_btn item_btn_del' onClick={this.handleDel.bind(this)}>删除</AtButton>
                <AtButton className='item_btn' onClick={this.handleFinish.bind(this)}>完成</AtButton>
              </View>
            }
            {Atstatus !== 0 &&
              <View className='b_mycollections__footer3'>
                <View className='b_mycollections__footer3_box' >
                  <Image src={Atstatus === 1 ? checkbox : checked} className='b_mycollections__footer3_img' onClick={this.handleAtSelAll.bind(this)}></Image>
                  <Text className='b_mycollections__footer3_text' onClick={this.handleAtSelAll.bind(this)}>全选</Text>
                </View>
                <AtButton className='item_btn item_btn_del' onClick={this.handleAtDel.bind(this)}>删除</AtButton>
                <AtButton className='item_btn' onClick={this.handleAtFinish.bind(this)}>完成</AtButton>
              </View>
            }
          </View>

        }
        <DModal
          isShow={isModal}
          title='提示'
          text={modelText}
          firstbtn='取消'
          lastbtn='确定'
          onCancel={this.handleCancel.bind(this)}
          onFirst={this.handleCancel.bind(this)}
          onLast={this.onHandlerConfirm.bind(this)}
        ></DModal>
      </View>

    )
  }
}
